package com.nx.platform.es.biz.esspider.handler;

import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.nx.platform.es.biz.esspider.entity.Item;
import com.nx.platform.es.biz.esspider.expression.Expression;
import com.nx.platform.es.common.utils.MoreMaps;

import java.util.Map;

/**
 * 根据表达式判断结果设置字段值
 *
 * @author
 * @date 2018/04/24
 */
@HandlerDefine(HandlerType.SIMPLE)
public class SimpleExpressionToBooleanHandler extends AbstractSimpleHandler {

    private String field;
    private Expression expression;

    @Override
    public void init(Map<?, ?> settings) throws Exception {
        field = MoreMaps.getString(settings, "field");
        expression = Expression.create(MoreMaps.getString(settings, "expression"));
        Preconditions.checkArgument(!Strings.isNullOrEmpty(field), "field null or empty");
    }

    @Override
    public void handle(Map<Long, Item> items) throws Exception {
        items.forEach((key, value) -> value.getDoc().put(field, expression.eval(value.getDoc())));
    }

}
